package com.heima.article.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApCollectionBehaviorMapper;
import com.heima.article.service.ApCollectionBehaviorService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApCollectionBehaviorServiceImpl extends ServiceImpl<ApCollectionBehaviorMapper, ApCollection> implements ApCollectionBehaviorService {
@Autowired
private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        if(dto==null||dto.getEntryId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getType()==null||(dto.getType()!=0&&dto.getType()!=1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getOperation()==null||(dto.getOperation()!=0&&dto.getOperation()!=1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = (user == null)?null:user.getId();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEntryId(userId, dto.getEntryId().intValue());
        if (apBehaviorEntry==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有与之对应的实体对象");
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getEntryId())
                .eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if (apCollection==null){
            apCollection = new ApCollection();
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(new Date());
            save(apCollection);
        }else {
            if (dto.getOperation()==1)
                removeById(apCollection.getId());
        }
       return ResponseResult.okResult();
    }
}
